<template>
  <div class="finance-management">
    <div class="header">
      <div class="title-section">
        <h2>财务管理</h2>
        <div class="subtitle">管理和跟踪所有财务流动记录、报表和分析</div>
      </div>
      <div class="header-buttons">
        <el-button style="background-color: #253963; color: #fff" @click="handleAdd"
          >+ 添加记录</el-button
        >
      </div>
    </div>

    <!-- 搜索过滤区域 -->

    <el-card class="filter-section">
      <div class="filter-header" v-if="isMobileView">
        <div class="filter-title">筛选条件</div>
        <el-button link type="primary" @click="isFilterVisible = !isFilterVisible">
          {{ isFilterVisible ? "收起" : "展开" }}
          <el-icon><ArrowDown v-if="!isFilterVisible" /><ArrowUp v-else /></el-icon>
        </el-button>
      </div>

      <div class="filter-content" v-show="!isMobileView || isFilterVisible">
        <div class="filter-row">
          <div class="filter-item">
            <div class="filter-label">金额范围</div>
            <div class="filter-inputs">
              <el-input v-model="searchForm.minAmount" placeholder="最小" />
              <span class="filter-separator">-</span>
              <el-input v-model="searchForm.maxAmount" placeholder="最大" />
            </div>
          </div>
          <el-button
            style="background-color: #253963; color: #fff"
            class="filter-button"
            @click="handleSearch"
          >
            筛选
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片区域 -->
    <div class="statistics-section">
      <div class="section-header">
        <h3>财务概览</h3>
      </div>
      <div class="statistics-cards" :class="{ scrollable: isMobileView }">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">本日总支出</div>
              <div class="stat-amount">¥128,540</div>
              <div class="stat-change decrease">↓5% 较上月</div>
            </div>
            <div class="stat-icon">
              <el-icon><CreditCard /></el-icon>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">油费费用</div>
              <div class="stat-amount">¥42,680</div>
              <div class="stat-change decrease">↓8% 较上月</div>
            </div>
            <div class="stat-icon">
              <el-icon><Van /></el-icon>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">维修保养</div>
              <div class="stat-amount">¥36,820</div>
              <div class="stat-change increase">↑12% 较上月</div>
            </div>
            <div class="stat-icon">
              <el-icon><Tools /></el-icon>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">保险费用</div>
              <div class="stat-amount">¥24,500</div>
              <div class="stat-change decrease">↓3% 较上月</div>
            </div>
            <div class="stat-icon">
              <el-icon><Shield /></el-icon>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 费用明细表格 -->
    <el-card class="expense-table">
      <div class="table-header">
        <div class="table-title">费用明细</div>
      </div>

      <!-- PC端表格 -->
      <div class="desktop-table" v-if="!isMobileView">
        <el-table
          :data="expenseList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          style="width: 100%"
          v-loading="loading"
          border
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="日期" prop="date" width="100" sortable />
          <el-table-column label="车辆" prop="vehicle" width="180" />
          <el-table-column label="费用类型" prop="expenseType" width="120">
            <template #default="scope">
              <el-tag :type="getExpenseTypeTag(scope.row.expenseType)">
                {{ scope.row.expenseType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="120" sortable>
            <template #default="scope">
              <span class="amount">¥{{ scope.row.amount.toLocaleString() }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" prop="department" width="120" />
          <el-table-column label="经手人" prop="handler" width="100" />
          <el-table-column
            label="备注"
            prop="remark"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" link @click="confirmDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 移动端卡片列表 -->
      <div class="mobile-expense-list" v-else>
        <div
          v-for="(item, index) in expenseList.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )"
          :key="index"
          class="mobile-expense-item"
        >
          <div class="mobile-expense-header">
            <div class="mobile-expense-date">{{ item.date }}</div>
            <div class="mobile-expense-amount">¥{{ item.amount.toLocaleString() }}</div>
          </div>
          <div class="mobile-expense-content">
            <div class="mobile-expense-info">
              <div class="mobile-expense-type">
                <el-tag :type="getExpenseTypeTag(item.expenseType)" size="small">
                  {{ item.expenseType }}
                </el-tag>
              </div>
              <div class="mobile-expense-vehicle">{{ item.vehicle }}</div>
              <div class="mobile-expense-department">{{ item.department }}</div>
            </div>
            <div class="mobile-expense-actions">
              <el-button type="primary" size="small" @click="handleEdit(item)"
                >编辑</el-button
              >
              <el-button type="danger" size="small" @click="confirmDelete(item)"
                >删除</el-button
              >
            </div>
          </div>
          <div class="mobile-expense-footer" v-if="item.remark">
            <div class="mobile-expense-remark">备注: {{ item.remark }}</div>
          </div>
        </div>
        <div v-if="expenseList.length === 0" class="no-data">暂无数据</div>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[5, 8, 10]"
          :layout="
            isMobileView ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'
          "
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>

  <!-- 添加/编辑记录弹框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="isMobileView ? '95%' : '600px'"
    :close-on-click-modal="false"
    top="50px"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="isMobileView ? 'auto' : '100px'"
      :label-position="isMobileView ? 'top' : 'right'"
    >
      <el-form-item label="日期" prop="date">
        <el-date-picker
          v-model="formData.date"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="车辆" prop="vehicle">
        <el-select
          v-model="formData.vehicle"
          placeholder="请选择车辆"
          style="width: 100%"
        >
          <el-option
            v-for="item in vehicles"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="费用类型" prop="expenseType">
        <el-select
          v-model="formData.expenseType"
          placeholder="请选择费用类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in expenseTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input-number
          v-model="formData.amount"
          :precision="2"
          :step="100"
          :min="0"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="department">
        <el-select
          v-model="formData.department"
          placeholder="请选择部门"
          style="width: 100%"
        >
          <el-option
            v-for="item in departments"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经手人" prop="handler">
        <el-input v-model="formData.handler" placeholder="请输入经手人" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer" :class="{ 'mobile-dialog-footer': isMobileView }">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button style="background-color: #253963; color: #fff" @click="handleSubmit"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { DateModelType } from "element-plus";
import { getCai, addCai, updateCai, deleteCai } from "@/utils/api";

// 检测是否为移动端视图
const windowWidth = ref(window.innerWidth);
const isMobileView = computed(() => windowWidth.value < 768);

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener("resize", handleResize);
});

// 在组件卸载前移除事件监听
const onBeforeUnmount = () => {
  window.removeEventListener("resize", handleResize);
};

// 接口定义
interface SearchForm {
  startDate: string | null;
  endDate: string | null;
  expenseType: string;
  vehicle: string;
  department: string;
  minAmount: string;
  maxAmount: string;
}

interface ExpenseRecord {
  id: string;
  date: string;
  vehicle: string;
  expenseType: string;
  amount: number;
  department: string;
  handler: string;
  remark: string;
}

interface ExpenseFormData extends Omit<ExpenseRecord, "id"> {
  id?: string;
}

interface DepartmentRanking {
  department: string;
  amount: number;
}

// 状态定义
const searchForm = ref<SearchForm>({
  startDate: null,
  endDate: null,
  expenseType: "",
  vehicle: "",
  department: "",
  minAmount: "",
  maxAmount: "",
});

const isFilterVisible = ref(false); // 控制移动端筛选区域的显示/隐藏

const dialogVisible = ref(false);
const dialogTitle = ref("添加记录");
const formData = ref<ExpenseFormData>({
  date: "",
  vehicle: "",
  expenseType: "",
  amount: 0,
  department: "",
  handler: "",
  remark: "",
});

const formRules = {
  date: [{ required: true, message: "请选择日期", trigger: "change" }],
  vehicle: [{ required: true, message: "请选择车辆", trigger: "change" }],
  expenseType: [{ required: true, message: "请选择费用类型", trigger: "change" }],
  amount: [
    { required: true, message: "请输入金额", trigger: "blur" },
    { type: "number", message: "金额必须为数字", trigger: "blur" },
  ],
  department: [{ required: true, message: "请选择部门", trigger: "change" }],
  handler: [{ required: true, message: "请输入经手人", trigger: "blur" }],
};

const chartTimeRange = ref("month");
const rankingTimeRange = ref("day");
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 选项数据
const expenseTypes = [
  { value: "油费", label: "油费" },
  { value: "维修保养", label: "维修保养" },
  { value: "保险", label: "保险" },
  { value: "过路费", label: "过路费" },
  { value: "停车费", label: "停车费" },
];

const vehicles = [
  { value: "沪A12345 - 大众帕萨特", label: "沪A12345 - 大众帕萨特" },
  { value: "沪B67890 - 丰田凯美瑞", label: "沪B67890 - 丰田凯美瑞" },
];

const departments = [
  { value: "物流部", label: "物流部" },
  { value: "销售部", label: "销售部" },
  { value: "运营部", label: "运营部" },
];

const distributionChartData = {
  labels: ["油费", "维修保养", "保险", "过路费", "停车费", "其他费用"],
  datasets: [
    {
      data: [30, 25, 20, 10, 10, 5],
      backgroundColor: ["#FF9F43", "#FF4757", "#2196F3", "#FFEB3B", "#4CAF50", "#9C27B0"],
    },
  ],
};

// 费用明细数据
const expenseList = ref<ExpenseRecord[]>([]);

const formRef = ref();
const loading = ref(false);

// 方法定义
const resetForm = () => {
  formData.value = {
    date: "",
    vehicle: "",
    expenseType: "",
    amount: 0,
    department: "",
    handler: "",
    remark: "",
  };
  formRef.value?.resetFields();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchExpenseList();
};

const handleAdd = () => {
  dialogTitle.value = "添加记录";
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: ExpenseRecord) => {
  dialogTitle.value = "编辑记录";
  formData.value = { ...row };
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    if (formData.value.id) {
      // 编辑模式
      await updateCai(formData.value.id, formData.value);
      fetchExpenseList();
    } else {
      // 添加模式

      const id = expenseList.value.length + 1;
      const obj = { ...formData.value, id: id };

      console.log(formData.value);

      await addCai(formData.value);
      fetchExpenseList();
      total.value++;
    }

    ElMessage.success(formData.value.id ? "更新成功" : "添加成功");
    dialogVisible.value = false;
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    loading.value = false;
  }
};

const confirmDelete = async (row: ExpenseRecord) => {
  try {
    await ElMessageBox.confirm("删除后数据将无法恢复，是否确认删除？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
      center: true,
    });
    handleDelete(row.id);
  } catch {
    // 用户取消删除，不做任何操作
  }
};

// <<<<<<< HEAD
// const handleDelete = async (id) => {
//   console.log(id)

//   // await deleteCai(id)
//   // fetchExpenseList()
// }

// const fetchExpenseList = async () => {
//   const data = await getCai()
//   // 模拟后端数据
//   expenseList.value = [...data.data]
//   total.value = data.data.length
// =======
const handleDelete = async (id: string) => {
  console.log(id);
  await deleteCai(id);
  fetchExpenseList();
};

const fetchExpenseList = async () => {
  const data = await getCai();
  console.log(data.data);

  // 模拟后端数据
  expenseList.value = [...data.data];
  total.value = data.data.length;
};

// 监听分页变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchExpenseList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchExpenseList();
};

const getExpenseTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    油费: "warning",
    维修: "danger",
    保险: "info",
    过路费: "success",
  };
  return typeMap[type] || "";
};

onMounted(() => {
  fetchExpenseList();
});
</script>

<style scoped>
.finance-management {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.title-section h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.subtitle {
  color: #6b7280;
  font-size: 14px;
}

.header-buttons {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.filter-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.filter-content {
  padding: 16px;
}

.filter-row {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  color: #4b5563;
  font-size: 14px;
  width: 70px;
}

.filter-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-separator {
  color: #4b5563;
  font-size: 14px;
}

.filter-button {
  width: 120px;
}

.statistics-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.statistics-cards.scrollable {
  display: flex;
  overflow-x: auto;
  padding: 16px 0;
  gap: 16px;
  scroll-snap-type: x mandatory;
  -webkit-overflow-scrolling: touch;
}

.statistics-cards.scrollable .stat-card {
  min-width: 250px;
  flex: 0 0 auto;
  scroll-snap-align: start;
}

.statistics-cards.scrollable::-webkit-scrollbar {
  height: 4px;
}

.statistics-cards.scrollable::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.statistics-cards.scrollable::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.statistics-cards.scrollable::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-amount {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.stat-change {
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-icon {
  font-size: 24px;
  color: #6b7280;
  opacity: 0.5;
}

.increase {
  color: #10b981;
}

.decrease {
  color: #ef4444;
}

.charts-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.chart-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.chart-container {
  padding: 20px;
  height: 300px;
}

.department-ranking {
  margin-bottom: 24px;
}

.expense-table {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.table-info {
  color: #6b7280;
  font-size: 14px;
}

.pagination {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card) {
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
  background-color: #f9fafb;
  font-weight: 600;
  color: #4b5563;
}

:deep(.el-tag) {
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #f9fafb;
}

:deep(.el-pagination) {
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

/* 移动端适配样式 */
@media (max-width: 992px) {
  .statistics-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .charts-section {
    grid-template-columns: 1fr;
  }

  .filter-row {
    flex-direction: column;
    gap: 16px;
  }

  .filter-item {
    width: 100%;
  }

  .filter-button {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .finance-management {
    padding: 16px;
  }

  .header {
    flex-direction: column;
    gap: 16px;
  }

  .header-buttons {
    width: 100%;
  }

  .header-buttons .el-button {
    width: 100%;
  }

  .statistics-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  :deep(.el-table) {
    width: 100%;
    overflow-x: auto;
  }

  :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 576px) {
  .finance-management {
    padding: 12px;
  }

  .title-section h2 {
    font-size: 20px;
  }

  .subtitle {
    font-size: 12px;
  }

  .stat-amount {
    font-size: 20px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }

  :deep(.el-dialog__body) {
    padding: 16px;
  }

  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    padding: 0 0 8px;
    text-align: left;
    line-height: 1;
  }

  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }

  :deep(.el-date-editor.el-input),
  :deep(.el-date-editor.el-input__inner) {
    width: 100%;
  }

  :deep(.el-select) {
    width: 100%;
  }
}

.mobile-expense-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 16px;
}

.mobile-expense-item {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.mobile-expense-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.mobile-expense-date {
  font-weight: 500;
  color: #4b5563;
  font-size: 14px;
}

.mobile-expense-amount {
  font-weight: 600;
  color: #1f2937;
  font-size: 16px;
}

.mobile-expense-content {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mobile-expense-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.mobile-expense-vehicle {
  font-size: 14px;
  color: #4b5563;
  margin-top: 4px;
}

.mobile-expense-department {
  font-size: 12px;
  color: #6b7280;
}

.mobile-expense-actions {
  display: flex;
  gap: 8px;
}

.mobile-expense-footer {
  padding: 8px 16px;
  border-top: 1px solid #e5e7eb;
  background-color: #f9fafb;
}

.mobile-expense-remark {
  font-size: 12px;
  color: #6b7280;
}

.no-data {
  text-align: center;
  padding: 32px 0;
  color: #6b7280;
  font-size: 14px;
}

.mobile-dialog-footer {
  display: flex;
  width: 100%;
}

.mobile-dialog-footer .el-button {
  flex: 1;
}
</style>
